package cn.gz.ibix.ibix_library.http;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import cn.gz.ibix.ibix_library.bean.ResultBean;
import cn.gz.ibix.library.http.IConvertResponse;

/**
 * 项目名称：ibix_library
 * <br>类描述：当前业务数据转换处理
 * <br>创建人：htliu
 * <br>创建时间：2018/4/24 17:57
 * <br>修改人:
 * <br>修改时间：2018/4/24 17:57
 * <br>修改备注：
 * <br>@version
 */
public abstract class BaseConvertResponse<R> implements IConvertResponse<R> {

    protected Gson gson = new Gson();

    @Override
    public void handle(String json) {
        if (json == null || json.length() == 0) {
            this.onError(new NullPointerException("reponse 没有数据"));
            return;
        }
        JsonObject object = gson.fromJson(json, JsonObject.class);
        boolean success = ResultBean.Status.SUCCESS.name().equals(object.get("status").getAsString());
        if (success) {
            JsonElement data = object.get("data");
            R r = null;
            if (data != null) {
                r = handJson(data);
            }
            this.onSuccess(r);
        } else {
            this.onFail(object.get("message").getAsString());
        }
    }

    protected abstract R handJson(JsonElement data);
}
